package com.czy.keybordlib;

import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.io.UnsupportedEncodingException;


public class DefineKeyboardUtil {
    private Context mContext;
    private EditText mEditText;
    public LinearLayout llOther;
    private LatinKeyboard mSymbolsKeyboard;
    private LatinKeyboard mSymbolsShiftedKeyboard;
    private LatinKeyboard mQwertyKeyboard;
    private LatinKeyboard mQwertyShiftedKeyboard;
    private StockKeyboardView mKeyboardView;
    public boolean isNum = false;

    private StringBuilder mComposing = new StringBuilder();

    public DefineKeyboardUtil(Context mContext, EditText mEditText, LinearLayout llOther, StockKeyboardView mKeyboardView) {
        this.mContext = mContext;
        this.mEditText = mEditText;
        this.llOther = llOther;
        this.mKeyboardView = mKeyboardView;

        mQwertyKeyboard = new LatinKeyboard(mContext, R.xml.qwerty);
        mSymbolsKeyboard = new LatinKeyboard(mContext, R.xml.symbols);
        mSymbolsShiftedKeyboard = new LatinKeyboard(mContext, R.xml.symbols_shift);
        mQwertyShiftedKeyboard = new LatinKeyboard(mContext, R.xml.qwerty_shift);

        this.mKeyboardView.setKeyboard(mQwertyKeyboard);
        this.mKeyboardView.setEnabled(true);
        this.mKeyboardView.setPreviewEnabled(true);
        this.mKeyboardView.setOnKeyboardActionListener(listener);
    }

    private OnKeyboardActionListener listener = new OnKeyboardActionListener() {

        @Override
        public void swipeUp() {
            // TODO Auto-generated method stub

        }

        @Override
        public void swipeRight() {
            // TODO Auto-generated method stub

        }

        @Override
        public void swipeLeft() {
            // TODO Auto-generated method stub

        }

        @Override
        public void swipeDown() {
            // TODO Auto-generated method stub

        }

        @Override
        public void onText(CharSequence text) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onRelease(int primaryCode) {
            // TODO Auto-generated method stub
            if (primaryCode == Keyboard.KEYCODE_CANCEL) {
                hideKeyboard();
            }


        }

        @Override
        public void onPress(int primaryCode) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            // TODO Auto-generated method stub
            Editable editable = mEditText.getText();
            int start = mEditText.getSelectionStart();
            Log.e("primaryCode", "onKey---primaryCode==" + primaryCode);
            switch (primaryCode) {
                case Keyboard.KEYCODE_DELETE:
                    Log.e("yang", "KEYCODE_DELETE");
                    handleBackspace(editable, start);
                    break;
                case -3:
                    llOther.setVisibility(View.GONE);
                    Log.e("yang", "KEYCODE_SHIFT");
                    break;
                case -2:
                    Log.e("yang", "KEYCODE_MODE_CHANGE");
                    changeKeyTONum();
                    break;
                case -1:
                    changeKey();
                    break;
                default:
                    Log.e("yang", "default---primaryCode==" + primaryCode);
                    if (mKeyboardView.isShifted()) {
                        primaryCode = Character.toUpperCase(primaryCode);
                    }
                    if (isAlphabet(primaryCode - 4000)) {
                        String tmpStr = null;
                        try {
                            // 164
                            // 216 27 223 80   216 27 223 33    0-256
                            tmpStr = new String(new byte[]{(byte) -40, (byte) 27, (byte) -33, (byte) (primaryCode - 4000)}, "UTF-16BE");
                        } catch (UnsupportedEncodingException e) {
                            Log.e("yang", "e==" + e.toString());
                        }
                        editable.insert(start, tmpStr);
                        mComposing.append(tmpStr);
                    } else {
                        editable.insert(start, Character.toString((char) primaryCode));
                        mComposing.append(Character.toString((char) primaryCode));
                    }
                    //  updateShiftKeyState();
                    break;
            }
        }
    };


    private void handleBackspace(Editable editable, int start) {
        final int length = mComposing.length();
//        String s = editable.toString();
//        s = s.substring(s.length() - 1);
//        Editable editable2 = new SpannableStringBuilder(s);
//        Log.e("yang", "editable2---==" + editable2.toString().getBytes().length);
//        Log.e("yang", "editable2---byte---Length==" + editable2.toString().getBytes().length);
        if (length % 2 == 0) {
            try {
                mComposing.delete(length - 2, length);
                if (editable != null && editable.length() > 0) {
                    if (start > 0) {
                        editable.delete(start - 2, start);
                    }
                }
            } catch (Exception e) {
                if (editable != null && editable.length() > 0) {
                    if (start > 0) {
                        editable.delete(start - 1, start);
                    }
                }
            }

        } else {
            mComposing.delete(length - 1, length);
            if (editable != null && editable.length() > 0) {
                if (start > 0) {
                    editable.delete(start - 1, start);
                }
            }
        }
        // updateShiftKeyState();
    }

    private void updateShiftKeyState() {
        if (mKeyboardView != null && mQwertyShiftedKeyboard == mKeyboardView.getKeyboard()) {
            mKeyboardView.setShifted(false);
            mKeyboardView.setKeyboard(mQwertyKeyboard);
        }
    }


    private boolean isAlphabet(int code) {
        return code >= 0 && code <= 159;
    }

    public void clearEditTextContent() {
        if (mEditText != null) {
            Editable editable = mEditText.getText();
            int start = mEditText.getSelectionStart();
            if (start > 0) {
                editable.clear();
            }
        }

    }


    public void showKeyboard() {
        int visibility = mKeyboardView.getVisibility();
        if (visibility == View.GONE) {
            mKeyboardView.setVisibility(View.VISIBLE);
        }
    }

    public void hideKeyboard() {
        int visibility = mKeyboardView.getVisibility();
        if (visibility == View.VISIBLE) {
            mKeyboardView.setVisibility(View.GONE);
        }
    }

    public boolean isShowKeyboard() {
        int visibility = mKeyboardView.getVisibility();
        return visibility == View.VISIBLE;
    }

    private void changeKey() {
        Keyboard currentKeyboard = mKeyboardView.getKeyboard();
        if (currentKeyboard == mQwertyKeyboard) {
            Log.e("yang", "mQwertyKeyboard");
            mQwertyKeyboard.setShifted(true);
            mKeyboardView.setKeyboard(mQwertyShiftedKeyboard);
            mQwertyShiftedKeyboard.setShifted(true);
        } else if (currentKeyboard == mQwertyShiftedKeyboard) {
            Log.e("yang", "mQwertyShiftedKeyboard");
            mQwertyShiftedKeyboard.setShifted(false);
            mKeyboardView.setKeyboard(mQwertyKeyboard);
            mQwertyKeyboard.setShifted(false);
        } else if (currentKeyboard == mSymbolsKeyboard) {
            Log.e("yang", "mSymbolsKeyboard");
            mSymbolsKeyboard.setShifted(true);
            mKeyboardView.setKeyboard(mSymbolsShiftedKeyboard);
            mSymbolsShiftedKeyboard.setShifted(true);
        } else if (currentKeyboard == mSymbolsShiftedKeyboard) {
            Log.e("yang", "mSymbolsShiftedKeyboard");
            mSymbolsShiftedKeyboard.setShifted(false);
            mKeyboardView.setKeyboard(mSymbolsKeyboard);
            mSymbolsKeyboard.setShifted(false);
        }
    }


    private void changeKeyTONum() {
        if (isNum) {
            isNum = false;
            mKeyboardView.setKeyboard(mQwertyKeyboard);
        } else {
            isNum = true;
            mKeyboardView.setKeyboard(mSymbolsKeyboard);
        }
    }


}
